#!/usr/bin/env python3
"""
迷宫游戏主程序 - 整合迷宫生成器和BOSS战系统
包含完整的游戏流程：迷宫生成、路径探索、资源收集、BOSS战斗
"""

import os
import json
import time
from typing import Dict, List, Tuple, Optional
from core.maze_generator import PerfectMazeGenerator
from core.boss_battle_optimizer import BossBattleOptimizer
from core.custom_game_loader import CustomGameLoader

class MazeGame:
    """迷宫游戏主控制器"""
    
    def __init__(self):
        self.maze = None
        self.player_pos = None
        self.player_resources = 10  # 初始资源
        self.collected_resources = {}
        self.triggered_traps = []
        self.unlocked_locks = []
        self.boss_defeated = False
        self.game_completed = False
        
        # 自定义游戏模式
        self.custom_loader = None
        self.is_custom_mode = False
        
    def start_game(self):
        """开始游戏"""
        print("🎮 欢迎来到迷宫冒险游戏！")
        print("=" * 60)
        
        while True:
            print("\n📋 游戏菜单：")
            print("1. 生成新迷宫")
            print("2. 显示当前迷宫")
            print("3. 查看游戏状态")
            print("4. 模拟游戏流程")
            print("5. BOSS战策略分析")
            print("6. 保存游戏数据")
            print("7. 加载历史迷宫")
            print("8. 🆕 自定义游戏模式")
            print("9. 🧩 密码谜题解析")
            print("0. 退出游戏")
            
            choice = input("\n请选择操作 (0-9): ").strip()
            
            if choice == "1":
                self.generate_maze()
            elif choice == "2":
                self.display_maze()
            elif choice == "3":
                self.show_status()
            elif choice == "4":
                self.simulate_game()
            elif choice == "5":
                self.analyze_boss_strategy()
            elif choice == "6":
                self.save_game()
            elif choice == "7":
                self.load_maze()
            elif choice == "8":
                self.custom_game_mode()
            elif choice == "9":
                self.password_puzzle_mode()
            elif choice == "0":
                print("\n👋 感谢游玩！再见！")
                break
            else:
                print("❌ 无效选择，请重新输入！")
    
    def generate_maze(self):
        """生成新迷宫"""
        print("\n🏗️ 迷宫生成器")
        print("-" * 30)
        
        while True:
            try:
                size = int(input("请输入迷宫大小 (推荐7, 15, 21): "))
                if size < 5:
                    print("❌ 迷宫太小，至少需要5x5")
                    continue
                elif size > 31:
                    print("❌ 迷宫太大，最大支持31x31")
                    continue
                break
            except ValueError:
                print("❌ 请输入有效的数字")
        
        print(f"\n🎯 正在生成 {size}x{size} 迷宫...")
        self.maze = PerfectMazeGenerator(size)
        self.maze.generate_maze()
        
        # 初始化玩家状态
        self.player_pos = self.maze.start_pos
        self.player_resources = 10
        self.collected_resources = {}
        self.triggered_traps = []
        self.unlocked_locks = []
        self.boss_defeated = False
        self.game_completed = False
        
        print("✅ 迷宫生成完成！")
        self.display_maze()
    
    def display_maze(self):
        """显示迷宫"""
        if not self.maze:
            print("❌ 请先生成迷宫")
            return
        
        print("\n🗺️ 当前迷宫：")
        print("-" * 40)
        self.maze.print_maze()
        
        print("\n📍 图例说明：")
        print("S = 起点 | E = 终点 | B = BOSS | G = 资源")
        print("T = 陷阱 | L = 机关 | # = 墙壁 | 空格 = 通路")
        
        if self.maze.boss_pos:
            boss_info = self.maze.get_boss_battle_info()
            if boss_info:
                print(f"\n⚔️ BOSS信息：血量{boss_info['hp']}，预计{boss_info['min_rounds']}回合击败")
    
    def show_status(self):
        """显示游戏状态"""
        if not self.maze:
            print("❌ 请先生成迷宫")
            return
        
        print("\n📊 游戏状态")
        print("-" * 30)
        print(f"🧭 当前位置: {self.player_pos}")
        print(f"💎 总资源: {self.player_resources}")
        print(f"📦 已收集资源: {len(self.collected_resources)}")
        print(f"⚠️ 触发陷阱: {len(self.triggered_traps)}")
        print(f"🔓 解锁机关: {len(self.unlocked_locks)}")
        print(f"👹 BOSS状态: {'已击败' if self.boss_defeated else '未挑战'}")
        print(f"🏆 游戏状态: {'已完成' if self.game_completed else '进行中'}")
        
        if self.collected_resources:
            print(f"\n💰 资源详情: {self.collected_resources}")
    
    def simulate_game(self):
        """模拟完整游戏流程"""
        if not self.maze:
            print("❌ 请先生成迷宫")
            return
        
        print("\n🎲 开始模拟游戏流程...")
        print("=" * 40)
        
        # 重置玩家状态
        self.player_pos = self.maze.start_pos
        self.player_resources = 10
        self.collected_resources = {}
        self.triggered_traps = []
        self.unlocked_locks = []
        self.boss_defeated = False
        self.game_completed = False
        
        # 检查起点和终点是否存在
        if not self.maze.start_pos or not self.maze.exit_pos:
            print("❌ 迷宫缺少起点或终点")
            return
        
        # 模拟路径探索
        path = self.maze._find_path_bfs(self.maze.start_pos, self.maze.exit_pos)
        
        print(f"🧭 探索路径: 从{self.maze.start_pos}到{self.maze.exit_pos}")
        print(f"📏 路径长度: {len(path)}步")
        
        # 模拟收集资源和触发事件
        for i, pos in enumerate(path):
            print(f"\n第{i+1}步: 移动到{pos}")
            
            # 收集资源
            if pos in self.maze.resources:
                resource_value = self.maze.resources[pos]
                self.collected_resources[pos] = resource_value
                self.player_resources += 5  # 固定收集金币+5
                print(f"💰 收集到金币+5，总金币: {self.player_resources}")
            
            # 触发陷阱
            if pos in self.maze.traps:
                self.triggered_traps.append(pos)
                penalty = 3  # 固定损失3
                self.player_resources -= penalty
                print(f"⚠️ 触发陷阱！损失金币-3，剩余: {self.player_resources}")
            
            # 解锁机关
            if pos in self.maze.locks:
                print(f"\n🔐 遇到解谜机关！位置: {pos}")
                puzzle_result = self.maze.interact_with_lock(pos, self.player_resources)
                
                if puzzle_result["success"]:
                    self.unlocked_locks.append(pos)
                    self.player_resources -= puzzle_result["cost"]
                    print(f"✅ {puzzle_result['message']}")
                    print(f"💰 消耗金币-{puzzle_result['cost']}，剩余: {self.player_resources}")
                    print(f"🔍 解谜尝试次数: {puzzle_result['attempts']}")
                else:
                    print(f"❌ {puzzle_result['message']}")
                    if "cost" in puzzle_result:
                        self.player_resources -= puzzle_result["cost"]
                        print(f"💰 仍需消耗金币-{puzzle_result['cost']}，剩余: {self.player_resources}")
            
            # 遇到BOSS
            if pos == self.maze.boss_pos:
                print(f"\n👹 遇到BOSS！当前资源: {self.player_resources}")
                self.simulate_boss_battle()
            
            time.sleep(0.1)  # 模拟时间流逝
        
        # 到达终点
        if path[-1] == self.maze.exit_pos:
            self.game_completed = True
            print(f"\n🏆 恭喜！成功完成迷宫冒险！")
            print(f"📊 最终统计：")
            print(f"   💎 总资源: {self.player_resources}")
            print(f"   📦 收集资源: {len(self.collected_resources)}")
            print(f"   👹 BOSS战: {'胜利' if self.boss_defeated else '未遇到'}")
    
    def simulate_boss_battle(self):
        """模拟BOSS战斗"""
        if not self.maze:
            print("❌ 请先生成迷宫")
            return
            
        if not self.maze.boss_pos:
            print("❌ 迷宫中没有BOSS")
            return
        
        print("\n⚔️ 开始BOSS战斗！")
        print("-" * 30)
        
        # 使用当前资源进行BOSS战
        battle_result = self.maze.simulate_boss_battle(self.player_resources)
        
        if battle_result['success']:
            self.boss_defeated = True
            print(f"✅ {battle_result['message']}")
            print(f"🎯 胜利策略: {' -> '.join(battle_result['skill_sequence'])}")
            print(f"⏰ 战斗回合: {battle_result['rounds']}")
            
            # 战斗后资源清零（全力以赴）
            self.player_resources = 0
            print(f"💎 战斗后剩余资源: {self.player_resources}")
        else:
            print(f"❌ {battle_result['message']}")
            if 'suggestion' in battle_result:
                print(f"💡 {battle_result['suggestion']}")
    
    def analyze_boss_strategy(self):
        """分析BOSS战策略"""
        if not self.maze or not self.maze.boss_pos:
            print("❌ 请先生成包含BOSS的迷宫")
            return
        
        print("\n🎯 BOSS战策略分析")
        print("=" * 40)
        
        boss_info = self.maze.get_boss_battle_info()
        if boss_info:
            print(f"👹 BOSS位置: {boss_info['position']}")
            print(f"❤️ BOSS血量: {boss_info['hp']}")
            print(f"⏰ 最少回合: {boss_info['min_rounds']}")
            print(f"🎯 推荐策略: {boss_info['recommended_sequence']}")
        
        # 测试不同资源情况
        test_resources = [5, 10, 15, 20, 25, 30]
        print(f"\n📊 不同资源条件下的战斗模拟：")
        
        for resources in test_resources:
            print(f"\n💎 资源数量: {resources}")
            result = self.maze.simulate_boss_battle(resources)
            
            if result['success']:
                print(f"   ✅ 胜利! {result['rounds']}回合")
                print(f"   🎯 策略: {' -> '.join(result['skill_sequence'][:3])}...")
            else:
                print(f"   ❌ 失败! {result['message']}")
    
    def save_game(self):
        """保存游戏数据"""
        if not self.maze:
            print("❌ 请先生成迷宫")
            return
        
        filename = input("请输入保存文件名 (不含扩展名): ").strip()
        if not filename:
            filename = f"maze_game_{int(time.time())}"
        
        filename = f"{filename}.json"
        
        # 保存完整游戏状态
        game_data = {
            'maze_data': {
                'size': self.maze.size,
                'maze_matrix': self.maze.get_maze_matrix(),
                'start_pos': self.maze.start_pos,
                'exit_pos': self.maze.exit_pos,
                'resources': {f"{k[0]},{k[1]}": v for k, v in self.maze.resources.items()},
                'traps': [f"{pos[0]},{pos[1]}" for pos in self.maze.traps],
                'locks': [f"{pos[0]},{pos[1]}" for pos in self.maze.locks],
                'boss_pos': f"{self.maze.boss_pos[0]},{self.maze.boss_pos[1]}" if self.maze.boss_pos else None,
                'boss_info': self.maze.get_boss_battle_info()
            },
            'player_state': {
                'position': self.player_pos,
                'resources': self.player_resources,
                'collected_resources': {f"{k[0]},{k[1]}": v for k, v in self.collected_resources.items()},
                'triggered_traps': [f"{pos[0]},{pos[1]}" for pos in self.triggered_traps],
                'unlocked_locks': [f"{pos[0]},{pos[1]}" for pos in self.unlocked_locks],
                'boss_defeated': self.boss_defeated,
                'game_completed': self.game_completed
            },
            'timestamp': time.time()
        }
        
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(game_data, f, ensure_ascii=False, indent=2)
            print(f"✅ 游戏数据已保存到 {filename}")
        except Exception as e:
            print(f"❌ 保存失败: {e}")
    
    def load_maze(self):
        """加载历史迷宫"""
        # 列出可用的JSON文件
        json_files = [f for f in os.listdir('.') if f.endswith('.json')]
        
        if not json_files:
            print("❌ 没有找到可加载的迷宫文件")
            return
        
        print("\n📁 可用的迷宫文件：")
        for i, filename in enumerate(json_files, 1):
            print(f"{i}. {filename}")
        
        try:
            choice = int(input("请选择要加载的文件编号: ")) - 1
            if 0 <= choice < len(json_files):
                filename = json_files[choice]
                self.load_maze_from_file(filename)
            else:
                print("❌ 无效的文件编号")
        except ValueError:
            print("❌ 请输入有效的数字")
    
    def load_maze_from_file(self, filename: str):
        """从文件加载迷宫"""
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            # 检查文件格式
            if 'maze_data' in data:
                # 新格式（完整游戏数据）
                maze_data = data['maze_data']
                size = maze_data['size']
            else:
                # 旧格式（仅迷宫数据）
                size = data['size']
                maze_data = data
            
            # 重新创建迷宫对象
            self.maze = PerfectMazeGenerator(size)
            self.maze.size = size
            
            # 恢复迷宫数据
            if 'start_pos' in maze_data:
                self.maze.start_pos = tuple(maze_data['start_pos'])
            if 'exit_pos' in maze_data:
                self.maze.exit_pos = tuple(maze_data['exit_pos'])
            
            # 恢复资源、陷阱等
            if 'resources' in maze_data:
                self.maze.resources = {tuple(map(int, k.split(','))): v 
                                     for k, v in maze_data['resources'].items()}
            
            if 'traps' in maze_data:
                self.maze.traps = [tuple(map(int, pos.split(','))) 
                                 for pos in maze_data['traps']]
            
            if 'locks' in maze_data:
                self.maze.locks = [tuple(map(int, pos.split(','))) 
                                 for pos in maze_data['locks']]
            
            if maze_data.get('boss_pos'):
                self.maze.boss_pos = tuple(map(int, maze_data['boss_pos'].split(',')))
                if 'boss_info' in maze_data and maze_data['boss_info']:
                    self.maze.boss_hp = maze_data['boss_info']['hp']
                    self.maze.boss_strategy = maze_data['boss_info']['strategy']
            
            # 恢复玩家状态（如果有）
            if 'player_state' in data:
                player_state = data['player_state']
                self.player_pos = tuple(player_state['position'])
                self.player_resources = player_state['resources']
                self.boss_defeated = player_state['boss_defeated']
                self.game_completed = player_state['game_completed']
            else:
                # 重置玩家状态
                self.player_pos = self.maze.start_pos
                self.player_resources = 10
                self.boss_defeated = False
                self.game_completed = False
            
            print(f"✅ 成功加载迷宫: {filename}")
            self.display_maze()
            
        except Exception as e:
            print(f"❌ 加载失败: {e}")
    
    def custom_game_mode(self):
        """自定义游戏模式"""
        print("\n🆕 自定义游戏模式")
        print("=" * 40)
        print("支持JSON格式的自定义迷宫、BOSS群、线索、技能等")
        
        while True:
            print("\n📋 自定义游戏选项：")
            print("1. 📝 输入JSON数据")
            print("2. 📁 从文件加载")
            print("3. 🎯 输入测试数据")
            print("4. 🎮 开始自定义游戏")
            print("5. 📊 查看当前配置")
            print("0. 返回主菜单")
            
            choice = input("请选择操作 (0-5): ").strip()
            
            if choice == "1":
                self.input_custom_json()
            elif choice == "2":
                self.load_custom_from_file()
            elif choice == "3":
                self.use_test_data()
            elif choice == "4":
                self.start_custom_game()
            elif choice == "5":
                self.show_custom_config()
            elif choice == "0":
                break
            else:
                print("❌ 无效选择，请重新输入！")
    
    def input_custom_json(self):
        """输入自定义JSON数据"""
        print("\n📝 请输入JSON格式的游戏数据：")
        print("(输入完成后按Enter，然后输入'END'结束)")
        
        json_lines = []
        while True:
            line = input()
            if line.strip().upper() == "END":
                break
            json_lines.append(line)
        
        json_text = '\n'.join(json_lines)
        
        try:
            json_data = json.loads(json_text)
            self.custom_loader = CustomGameLoader()
            if self.custom_loader.load_from_json(json_data):
                self.is_custom_mode = True
                print("✅ 自定义游戏数据加载成功！")
            else:
                print("❌ 数据加载失败")
        except json.JSONDecodeError as e:
            print(f"❌ JSON格式错误: {e}")
        except Exception as e:
            print(f"❌ 加载失败: {e}")
    
    def load_custom_from_file(self):
        """从文件加载自定义数据"""
        filename = input("请输入JSON文件名: ").strip()
        
        if not filename.endswith('.json'):
            filename += '.json'
        
        try:
            self.custom_loader = CustomGameLoader()
            if self.custom_loader.load_from_file(filename):
                self.is_custom_mode = True
                print("✅ 自定义游戏数据加载成功！")
            else:
                print("❌ 文件加载失败")
        except Exception as e:
            print(f"❌ 加载失败: {e}")
    
    def use_test_data(self):
        """输入测试数据"""
        print("\n🎯 自定义测试数据输入")
        print("=" * 40)
        print("请按照提示逐步输入测试数据：")
        
        try:
            # 输入迷宫大小
            size = int(input("\n请输入迷宫大小 (例如: 15): "))
            if size < 5 or size > 31:
                print("❌ 迷宫大小应在5-31之间")
                return
            
            # 输入线索
            print("\n请输入密码线索 (格式: [[1,0],[-1,-1]]): ")
            clues_input = input().strip()
            clues = json.loads(clues_input)
            
            # 输入BOSS群血量
            print("\n请输入BOSS群血量 (格式: [40,60,80]): ")
            boss_hp_input = input().strip()
            boss_hp = json.loads(boss_hp_input)
            
            # 输入玩家技能
            print("\n请输入玩家技能 (格式: [[12,2],[20,3],[8,1]]): ")
            skills_input = input().strip()
            skills = json.loads(skills_input)
            
            # 输入密码哈希
            print("\n请输入目标密码哈希值: ")
            target_hash = input().strip()
            
            # 生成简单的测试迷宫
            maze_matrix = [["#"] * size for _ in range(size)]
            
            # 设置基本路径
            for i in range(1, size-1):
                for j in range(1, size-1):
                    if (i + j) % 2 == 1:  # 创建棋盘模式的通路
                        maze_matrix[i][j] = " "
            
            # 设置起点和终点
            maze_matrix[1][1] = "S"
            maze_matrix[size-2][size-2] = "E"
            
            # 添加一些游戏元素
            if size >= 7:
                maze_matrix[size//2][size//2] = "B"  # BOSS
                maze_matrix[3][3] = "G"              # 资源
                maze_matrix[size-4][3] = "T"         # 陷阱
                maze_matrix[3][size-4] = "L"         # 机关
                if size >= 11:
                    maze_matrix[size-3][size//2] = "G"  # 更多资源
            
            test_data = {
                "maze": maze_matrix,
                "C": clues,
                "B": boss_hp,
                "PlayerSkills": skills,
                "L": target_hash
            }
            
            print("\n🎯 加载测试数据...")
            self.custom_loader = CustomGameLoader()
            if self.custom_loader.load_from_json(test_data):
                self.is_custom_mode = True
                print("✅ 测试数据加载成功！")
                print(f"🗺️ 生成了{size}x{size}的测试迷宫")
            else:
                print("❌ 测试数据加载失败")
                
        except json.JSONDecodeError:
            print("❌ JSON格式错误，请检查输入格式")
        except ValueError:
            print("❌ 数值输入错误")
        except Exception as e:
            print(f"❌ 输入失败: {e}")
    
    def show_custom_config(self):
        """显示当前自定义配置"""
        if not self.custom_loader:
            print("❌ 尚未加载自定义游戏数据")
            return
        
        print("\n📊 当前自定义游戏配置：")
        print("-" * 40)
        
        summary = self.custom_loader.get_game_summary()
        print(f"🗺️ 迷宫: {'已加载' if summary['maze_loaded'] else '未加载'}")
        if summary['maze_loaded']:
            print(f"   大小: {summary['maze_size']}x{summary['maze_size']}")
        
        print(f"👹 BOSS群: {summary['boss_count']}个BOSS")
        print(f"🔍 线索: {summary['clue_count']}个线索")
        print(f"⚔️ 技能: {summary['skill_count']}个自定义技能")
        print(f"🧩 密码谜题: {'是' if summary['has_password_puzzle'] else '否'}")
        print(f"💰 金币: {summary['player_coins']}")
        print(f"🔐 密码尝试次数: {summary['password_attempts']}")
        
        # 显示迷宫（如果加载了）
        if summary['maze_loaded']:
            print("\n🗺️ 自定义迷宫预览：")
            maze_info = self.custom_loader.get_maze_info()
            for row in maze_info['maze_matrix']:
                print(' '.join(row))
    
    def start_custom_game(self):
        """开始自定义游戏"""
        if not self.custom_loader:
            print("❌ 请先加载自定义游戏数据")
            return
        
        print("\n🎮 开始自定义游戏！")
        print("=" * 40)
        
        # 显示游戏概况
        summary = self.custom_loader.get_game_summary()
        print(f"🗺️ 迷宫大小: {summary['maze_size']}x{summary['maze_size']}")
        print(f"👹 BOSS数量: {summary['boss_count']}")
        print(f"🔍 线索数量: {summary['clue_count']}")
        
        # 解密码谜题
        if summary['has_password_puzzle']:
            print(f"\n🧩 第一阶段：密码谜题")
            password = self.custom_loader.solve_password_puzzle()
            if not password:
                print("❌ 密码谜题失败，游戏结束")
                return
        
        # BOSS群战斗
        if summary['boss_count'] > 0:
            print(f"\n⚔️ 第二阶段：BOSS群战斗")
            initial_resources = 20  # 自定义游戏初始资源
            battle_result = self.custom_loader.simulate_boss_group_battle(initial_resources)
            
            if battle_result['success']:
                print(f"✅ {battle_result['message']}")
                print(f"⏰ 总回合数: {battle_result['total_rounds']}")
                print(f"🏆 成功击败{battle_result['boss_count']}个BOSS！")
            else:
                print(f"❌ {battle_result['message']}")
                return
        
        print(f"\n🎉 恭喜！自定义游戏挑战成功！")
    
    def password_puzzle_mode(self):
        """密码谜题模式（仅支持带盐值哈希）"""
        print("\n🧩 密码谜题解析模式")
        print("=" * 40)
        
        while True:
            print("\n📋 密码谜题选项：")
            print("1. 🔒 密码谜题求解")
            print("2. 🧪 生成测试用例")
            print("3. 🎯 测试密码锁集成")
            print("0. 返回主菜单")
            
            choice = input("请选择操作 (0-3): ").strip()
            
            if choice == "1":
                self._solve_salted_hash()
            elif choice == "2":
                self._generate_salted_test_case()
            elif choice == "3":
                self._test_password_lock_integration()
            elif choice == "0":
                break
            else:
                print("❌ 无效选择，请重新输入！")
    
    def _solve_salted_hash(self):
        """带盐值哈希求解"""
        print("📝 请输入带盐值密码谜题数据")
        
        # 输入线索
        print("请输入线索 (格式: [[1,0],[-1,-1]]):")
        try:
            clues_input = input().strip()
            clues = json.loads(clues_input)
            
            # 输入带盐值哈希
            print("请输入带盐值的目标哈希值:")
            target_hash = input().strip()
            
            # 创建临时加载器求解
            temp_loader = CustomGameLoader()
            temp_loader.clues = clues
            temp_loader.target_hash = target_hash
            
            result = temp_loader.solve_password_puzzle()
            if result:
                print(f"🎉 密码破解成功: {result}")
            else:
                print("❌ 密码破解失败")
                
        except json.JSONDecodeError:
            print("❌ 输入格式错误")
        except Exception as e:
            print(f"❌ 解析失败: {e}")
    
    def _generate_salted_test_case(self):
        """生成带盐值测试用例"""
        print("🧪 生成带盐值哈希测试用例")
        
        password = input("请输入要生成哈希的密码: ").strip()
        
        try:
            temp_loader = CustomGameLoader()
            salted_hash = temp_loader.create_salted_hash_test_case(password)
            
            print(f"✅ 带盐值哈希生成成功:")
            print(f"   原始密码: {password}")
            print(f"   盐值哈希: {salted_hash}")
            print(f"   用法: 可将此哈希值用于带盐值密码谜题")
            
        except Exception as e:
            print(f"❌ 生成失败: {e}")
    
    def _test_password_lock_integration(self):
        """测试密码锁集成"""
        print("🧪 测试密码锁集成功能")
        
        try:
            from core.puzzle_solver import PuzzleSolver
            solver = PuzzleSolver()
            solver.test_password_lock_integration()
            
        except Exception as e:
            print(f"❌ 测试失败: {e}")


def main():
    """主函数"""
    print("🎮 迷宫冒险游戏 v2.0")
    print("🎯 集成迷宫生成器和BOSS战策略优化器")
    print("📝 支持完整的游戏流程模拟和策略分析")
    
    game = MazeGame()
    try:
        game.start_game()
    except KeyboardInterrupt:
        print("\n\n👋 游戏被用户中断，再见！")
    except Exception as e:
        print(f"\n❌ 游戏出现错误: {e}")
        print("请检查代码或重新启动游戏")


if __name__ == "__main__":
    main() 